<template>
	<view class="bind-phone">
		<view class="phone">
			<view class="phone-item">
				<text class="label">手机号:</text>
				<input type="number" v-model="formData.mobile" maxlength="11" placeholder="请输入手机号码" />
			</view>
			<view class="phone-item">
				<text class="label">验证码:</text>
				<view class="get-code">
					<input type="number" v-model="formData.code" maxlength="6" placeholder="请输入验证码" />
					<l-code :mobile="formData.mobile" :templateCode="'SMS_1231312312'"></l-code>
				</view>
			</view>
		</view>

		<button type="primary" @click="handleSubmit">提交</button>
	</view>
</template>

<script>
	import {
		AuthModel
	} from "@/common/apis/auth.js"
	let authModel = new AuthModel()

	export default {
		data() {
			return {
				formData: {
					mobile: '',
					code: '',
					data: {},
					editMobile: false
				}
			}
		},
		onLoad(options) {
			if (options.editMobile) this.editMobile = options.editMobile
			options.title && uni.setNavigationBarTitle({
				title: options.title
			})
			this.data = options.data && JSON.parse(options.data)
		},
		methods: {
			//修改手机号方法
			async handleSubmit() {
				if (!this.formData.mobile || !this.$util.checkStr(this.formData.mobile, 'mobile')) {
					this.$util.msg('请输入有效手机号码')
					return
				}
				if (!this.formData.code || !this.$util.checkStr(this.formData.code, 'mobileCode')) {
					this.$util.msg('验证码输入错误')
					return
				}
				uni.showLoading({
					mask: true
				})
				let res = null
				try {
					if (this.editMobile) {
						res = await authModel.updateMobile({ ...this.formData })
						
						console.log(res)
						
					} else {
						// 更新绑定手机号
						res = await authModel.bindMobile({
							...this.formData,
							...data
						})
					}
					uni.hideLoading()
					this.$util.msg(res.data.message)
					if (res.data.code !== 20000) return
					this.bindUpdateStore(res.data.data)
				} catch (e) {
					this.$util.msg('操作失败')
				}

			},

			// 绑定成功, 更新store登录状态
			bindUpdateStore(data) {
				// this.$util.msg('绑定成功')
				this.$store.commit('setToken', data)
				setTimeout(() => {
					this.navBack(2)
				}, 500)
			},

		}
	}
</script>

<style lang="scss">
	page {
		height: 100%;
		background-color: $mxg-color-grey;
	}

	.bind-phone {
		padding: 40rpx;

		.phone {
			margin-top: 40rpx;
			background-color: #fff;
			border-radius: 20rpx;
			margin-bottom: 80rpx;

			.phone-item {
				padding: 20rpx;
				display: flex;
				align-items: center;

				.label {
					font-size: 36rpx;
					margin-right: 20rpx;
					display: block;
					width: 150rpx;
				}

				input {
					font-size: 36rpx;
					flex: 1;
				}

				.get-code {
					position: relative;
					flex: 1;
				}
			}
		}
	}
</style>
